package com.xiaoyu.lanling.feature.login.activity

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.data.ConfigData
import com.xiaoyu.lanling.event.login.LockMessageEvent
import com.xiaoyu.lanling.feature.login.data.LoginData
import com.xiaoyu.lanling.feature.login.model.LockModel
import com.xiaoyu.lanling.router.deeplink.DeepLinkRouter
import kotlinx.android.synthetic.main.activity_lock.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class LockActivity : AppCompatToolbarActivity() {

    private val requestTag = Any()

    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState)
        setLightStatusBar()
        setContentView(R.layout.activity_lock)
        initToolbar()

        initBind()
        initEvent()
        initData()
    }

    private fun initBind() {
        user_protocol.setOnClickDebounceListener {
            val protocolUrl = ConfigData.getInstance().getUrl("userProtocol")
            DeepLinkRouter.getInstance().dispatch(this, protocolUrl)
        }
        privacy_protocol.setOnClickDebounceListener {
            val protocolUrl = ConfigData.getInstance().getUrl("privacyProtocol")
            DeepLinkRouter.getInstance().dispatch(this, protocolUrl)
        }
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: LockMessageEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                showData(event.model)
            }
        })
    }

    private fun showData(model: LockModel) {
        reason.text = model.disableMessage
        unlock_time_desc.visibility = if (TextUtils.isEmpty(model.unlockTime)) View.GONE else View.VISIBLE
        unlock_time_desc.text = getString(R.string.login_lock_unlock_time, model.unlockTime)
    }

    private fun initData() {
        val cellphone = intent.getStringExtra(Constant.IntentKey.KEY_LOGIN_CELLPHONE) ?: return
        val openId = intent.getStringExtra(Constant.IntentKey.KEY_LOGIN_OPEN_ID) ?: return
        LoginData.lockMessage(requestTag, cellphone, openId)
    }
}